//
//  M1PhotoGalleryVC.m
//  NewMarryU
//
//  Created by Cedar on 2018/7/16.
//  Copyright © 2018年 Cedar. All rights reserved.
//

#import "M1PhotoGalleryVC.h"
#import "M1PhotoAlbumLayout.h"
#import "M1PhotoAlbumCell.h"
#import "KSPhotoBrowser.h"
#import "MLImageCrop.h"
#import "MJRefresh.h"


@interface M1PhotoGalleryVC ()<UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, KSPhotoBrowserDelegate, MLImageCropDelegate, UIImagePickerControllerDelegate,UINavigationControllerDelegate>

@property (nonatomic, assign) BOOL m1_status;;

@property (nonatomic, assign) NSInteger m1_page;

@property (nonatomic, strong) UICollectionView *m1_collectionView;

@property (nonatomic, strong) NSMutableArray *m1_pathArr;

@property (strong, nonatomic) M1PhotoAlbumLayout *m1_layout;

@end

@implementation M1PhotoGalleryVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.title = @"照片墙";
    
    self.m1_page = 1;
    
    self.m1_status = NO;
    
    self.m1_pathArr = [NSMutableArray arrayWithCapacity:0];
    
    [self m1_createUI];
    
    [self m1_requestData];
}

- (void)m1_requestData{
    WEAKSELF
    [M1HttpNet requestWithMethod:m1_photo_list_url params:@{@"page":@"1", @"uid":[M1User user].basic.uid, @"count":@"15"} success:^(id resDic, NSInteger code, NSString *message) {
        [weakSelf.m1_pathArr removeAllObjects];
        [weakSelf.m1_pathArr addObjectsFromArray:resDic];
        [weakSelf.m1_collectionView reloadData];
        [weakSelf.m1_collectionView.mj_header endRefreshing];
    } fail:^(id resDic, NSInteger code, NSString *message) {
        [weakSelf.m1_collectionView.mj_header endRefreshing];
    } showAni:YES];
}

- (void)m1_requestMoreData{
    self.m1_page ++;
    WEAKSELF
    [M1HttpNet requestWithMethod:m1_photo_list_url params:@{@"page":@(_m1_page), @"uid":[M1User user].basic.uid, @"count":@"15"} success:^(id resDic, NSInteger code, NSString *message) {
        if ([resDic count] > 0) {
            [weakSelf.m1_pathArr addObjectsFromArray:resDic];
            [weakSelf.m1_collectionView reloadData];
        }else{
            weakSelf.m1_page--;
        }
        [weakSelf.m1_collectionView.mj_footer endRefreshing];
    } fail:^(id resDic, NSInteger code, NSString *message) {
        weakSelf.m1_page--;
        [weakSelf.m1_collectionView.mj_footer endRefreshing];
    } showAni:YES];
}

#pragma mark - KSPhotoBrowserDelegate
- (void)ks_photoBrowser:(KSPhotoBrowser *)browser didSelectItem:(KSPhotoItem *)item atIndex:(NSUInteger)index {
    NSLog(@"selected index: %ld", index);
}

- (void)ks_delete_photoBrowser:(KSPhotoBrowser *)browser didSelectItem:(KSPhotoItem *)item atIndex:(NSUInteger)index{
    NSLog(@"删除: %ld", index);
    NSDictionary *dic = self.m1_pathArr[index + 1];
    WEAKSELF
    [M1HttpNet requestWithMethod:m1_user_photo_del_url params:@{@"id":[dic m1_stringKey:@"id"]} success:^(id resDic, NSInteger code, NSString *message) {
        [weakSelf.m1_pathArr removeObjectAtIndex:index + 1];
        [weakSelf.m1_collectionView reloadData];
        [weakSelf dismissViewControllerAnimated:YES completion:^{
        }];
    } fail:^(id resDic, NSInteger code, NSString *message) {
        [weakSelf dismissViewControllerAnimated:YES completion:^{
            [M1Alert m1_alertWithTitle:nil message:message];
        }];
    } showAni:YES];
}

- (void)ks_cover_photoBrowser:(KSPhotoBrowser *)browser didSelectItem:(KSPhotoItem *)item atIndex:(NSUInteger)index{
    NSLog(@"上传封面: %ld", index);
    MLImageCrop *imageCrop = [[MLImageCrop alloc]init];
    imageCrop.delegate = self;
    imageCrop.ratioOfWidthAndHeight = 600.0f/600.0f;
    imageCrop.imageURL = [NSURL URLWithString:_m1_pathArr[index + 1][@"img"][@"url"]];
    imageCrop.sid = _m1_pathArr[index + 1][@"id"];
    [imageCrop showWithAnimation:NO];
    
}

- (void)ks_share_photoBrowser:(KSPhotoBrowser *)browser didSelectItem:(KSPhotoItem *)item atIndex:(NSUInteger)index{
    NSLog(@"分享: %ld", index);
}

#pragma mark - crop delegate
- (void)cropImage:(UIImage*)cropImage forOriginalImage:(UIImage*)originalImage sid:(NSString *)sid
{
    WEAKSELF
    [[M1FileUpload manager] m1_uploadImages:@[cropImage] progress:^(CGFloat progress) {
        
    } completion:^(NSArray<NSString *> * _Nullable urls, NSArray<NSDictionary *> * _Nullable pictures, NSError * _Nullable error) {
        
            [weakSelf m1_requestImagePhoto:urls];
        
    }];
}

#pragma mark - collectionDelegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.item == 0) {
        M1SheetView *m1_sheet = [[M1SheetView alloc] initWithTitles:@[@"拍照",@"从相册选择"]];
        [m1_sheet m1_show];
        
        WEAKSELF
        m1_sheet.click = ^(NSInteger index) {
            
            UIImagePickerControllerSourceType sourceType;
            
            if (index == 0) {
                weakSelf.m1_status = NO;
                AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
                if(authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied){
                    NSString *errorStr = @"应用相机权限受限,请在设置中启用";
                    return;
                }else{
                    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
                        sourceType = UIImagePickerControllerSourceTypeCamera;
                    }
                }
            }else{
                if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
                    sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                }
            }
            UIImagePickerController *m1_picker = [[UIImagePickerController alloc] init];
            m1_picker.editing = YES;
            m1_picker.sourceType = sourceType;
            m1_picker.delegate = weakSelf;
            m1_picker.allowsEditing = YES;
            if (index == 0) {
                m1_picker.cameraDevice = UIImagePickerControllerCameraDeviceFront;
            }
            
            [weakSelf presentViewController:m1_picker animated:YES completion:nil];
        };
    }else if (indexPath.item > 0 && indexPath.item < 3) {
        
    }else if (indexPath.item == (self.m1_pathArr.count?self.m1_pathArr.count + 2 :3)){
        M1SheetView *m1_sheet = [[M1SheetView alloc] initWithTitles:@[@"拍照",@"从相册选择"]];
        [m1_sheet m1_show];
        WEAKSELF
        m1_sheet.click = ^(NSInteger index) {
            if (index == 0) {
                weakSelf.m1_status = YES;
                UIImagePickerController *m1_picker = [[UIImagePickerController alloc] init];
                m1_picker.editing = YES;
                m1_picker.sourceType = UIImagePickerControllerSourceTypeCamera;
                m1_picker.delegate = weakSelf;
                m1_picker.allowsEditing = YES;
                if (index == 0) {
                    m1_picker.cameraDevice = UIImagePickerControllerCameraDeviceFront;
                }
                
                
                
                [weakSelf presentViewController:m1_picker animated:YES completion:nil];
            }else if (index == 1){
                [[M1ImagePick manager] m1_pickImages:^(NSArray *photos) {
                    [[M1FileUpload manager] m1_uploadImages:photos progress:^(CGFloat progress) {
                        
                    } completion:^(NSArray<NSString *> * _Nullable urls, NSArray<NSDictionary *> * _Nullable pictures, NSError * _Nullable error) {
                        [weakSelf m1_addImagePhoto:urls];
                    }];
                } type:index maxCount:9 vc:weakSelf];
            }
        };
    }else{
        NSMutableArray *items = @[].mutableCopy;
        for (int i = 1; i < _m1_pathArr.count; i++) {
            M1PhotoAlbumCell *cell = (M1PhotoAlbumCell *)[collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForRow:i + 2 inSection:0]];
            KSPhotoItem *item = [KSPhotoItem itemWithSourceView:cell.m1_photoImage imageUrl:[NSURL URLWithString:_m1_pathArr[i][@"img"][@"url"]]];
            [items addObject:item];
        }
        KSPhotoBrowser *browser = [KSPhotoBrowser browserWithPhotoItems:items selectedIndex:indexPath.row - 3];
        browser.delegate = self;
        browser.dismissalStyle = KSPhotoBrowserInteractiveDismissalStyleRotation;
        browser.backgroundStyle = KSPhotoBrowserBackgroundStyleBlur;
        browser.loadingStyle = KSPhotoBrowserImageLoadingStyleIndeterminate;
        browser.pageindicatorStyle = KSPhotoBrowserPageIndicatorStyleNone;
        browser.bounces = YES;
        [browser showFromViewController:self];
    }
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    NSInteger number = 4;
    
    if (self.m1_pathArr.count > 0) {
        number = self.m1_pathArr.count + 3;
    }
    
    return number;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    M1PhotoAlbumCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:m1_tableViewCellIdentifier forIndexPath:indexPath];
    if (indexPath.item == 0) {
        if (self.m1_pathArr.count > 0) {
            NSDictionary *dic = [self.m1_pathArr firstObject];
            
            [cell.m1_photoImage sd_setImageWithURL:[NSURL URLWithString:dic[@"img"][@"url"]] placeholderImage:LOAD_LOCAL_IMG(@"bgView")];
        }else{
            [cell.m1_photoImage sd_setImageWithURL:[NSURL URLWithString:[M1User user].basic.avatar.img.url] placeholderImage:LOAD_LOCAL_IMG(@"bgView")];
        }
    }
    
    
    if (indexPath.item > 2) {
        if (self.m1_pathArr.count > 0) {
            if (indexPath.item == self.m1_pathArr.count + 2) {
                cell.m1_photoImage.image = LOAD_LOCAL_IMG(@"personal_icon_pianku");
            }else{
                NSDictionary *dic = self.m1_pathArr[indexPath.item - 2];
                [cell.m1_photoImage sd_setImageWithURL:[NSURL URLWithString:dic[@"img"][@"url"]] placeholderImage:LOAD_LOCAL_IMG(@"bgView")];
            }
        }else{
            if (indexPath.item == 3) {
                cell.m1_photoImage.image = LOAD_LOCAL_IMG(@"personal_icon_pianku");
            }
        }
    }
    
    if (indexPath.item == 1 || indexPath.item == 2) {
        cell.hidden = YES;
    }else{
        cell.hidden = NO;
    }
    
    return cell;
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    return UIEdgeInsetsMake(7, 7, 7, 7);
}

#pragma mark - imagePickerController delegate

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    
    [picker dismissViewControllerAnimated:YES completion:nil];
    //获取到的图片
    UIImage * image = [info valueForKey:UIImagePickerControllerEditedImage];
    
    WEAKSELF
    [[M1FileUpload manager] m1_uploadImages:@[image] progress:^(CGFloat progress) {
        
    } completion:^(NSArray<NSString *> * _Nullable urls, NSArray<NSDictionary *> * _Nullable pictures, NSError * _Nullable error) {
        
        if (weakSelf.m1_status) {
            [weakSelf m1_addImagePhoto:urls];
        }else{
            [weakSelf m1_requestImagePhoto:urls];
        }
    }];
}

- (void)m1_requestImagePhoto:(NSArray *)path{
    
    NSError *error = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:@{@"pic":[path firstObject]}
                                                       options:NSJSONWritingPrettyPrinted
                                                         error:&error];
    
    WEAKSELF
    [M1HttpNet requestWithMethod:m1_update_info_url params:@{@"avatar":jsonData} success:^(id resDic, NSInteger code, NSString *message) {
        if (weakSelf.m1_pathArr.count > 0){
            [weakSelf.m1_pathArr replaceObjectAtIndex:0 withObject:@{@"img":@{@"url":[path firstObject]}}];
        }else{
            [weakSelf m1_requestData];
        }
        [weakSelf.m1_collectionView reloadData];
        [weakSelf dismissViewControllerAnimated:NO completion:^{
            [M1Alert m1_alertWithTitle:nil message:@"设置成功"];
        }];
        
        [M1User m1_uploadInfo:^(M1User *user) {
        }];
    } fail:^(id resDic, NSInteger code, NSString *message) {
        [M1Alert m1_alertWithTitle:nil message:message];
    } showAni:YES];
}

- (void)m1_addImagePhoto:(NSArray *)urlArr{
    
    NSMutableArray *items = [NSMutableArray arrayWithCapacity:0];
    
    for (NSString *url in urlArr) {
        [items addObject:@{@"pic":url}];
    }
    
    NSError *error = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:items
                                                       options:NSJSONWritingPrettyPrinted
                                                         error:&error];
    
    NSDictionary *params = @{@"content":jsonData};
    
    WEAKSELF
    [M1HttpNet requestWithMethod:m1_user_photos_url params:params success:^(id resDic, NSInteger code, NSString *message) {
        [weakSelf m1_requestData];
        [M1User m1_uploadInfo:^(M1User *user) {
        }];
    } fail:^(id resDic, NSInteger code, NSString *message) {
        
    } showAni:YES];
}

- (void)m1_createUI{
    self.m1_collectionView.collectionViewLayout = self.m1_layout;
    self.m1_collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:self.m1_layout];
    _m1_collectionView.backgroundColor = [UIColor clearColor];
    _m1_collectionView.dataSource = self;
    _m1_collectionView.delegate = self;
    [_m1_collectionView registerNib:[UINib nibWithNibName:@"M1PhotoAlbumCell" bundle:[NSBundle mainBundle]] forCellWithReuseIdentifier:m1_tableViewCellIdentifier];
    
    [self.view addSubview:_m1_collectionView];
    
    [self.m1_collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(UIEdgeInsetsMake(STATUS_HEIGHT + 44, 0, iPhoneX?35:0, 0));
    }];
    
    [self.m1_layout m1_computeIndexCellHeightWithWidthBlock:^CGFloat(NSIndexPath *indexPath, CGFloat width) {
        
        int randomNum = 0;
        
        if (indexPath.item == 0) {
            randomNum = (SCREENWIDTH - 28) / 3 * 2 + 6;
        }else{
            randomNum = (SCREENWIDTH - 28) / 3;
        }
        
        return (CGFloat)randomNum;
    }];
    
    WEAKSELF
    self.m1_collectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        weakSelf.m1_page = 1;
        [weakSelf m1_requestData];
    }];
    self.m1_collectionView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        [weakSelf m1_requestMoreData];
    }];
    
}

- (M1PhotoAlbumLayout *)m1_layout {
    if (!_m1_layout) {
        _m1_layout = [[M1PhotoAlbumLayout alloc] init];
        
    }
    return _m1_layout;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
